from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.forms import ModelForm
from django.shortcuts import render, redirect
from django import forms
from django.utils.safestring import mark_safe

from app01 import models
from app01.models import Department
from app01.utils.pagination import Pagination
from app01.utils.bootstrap import BootstrapModelForm

# Create your views here.


def depart_list(request):
    """部门列表"""

    depart_list = Department.objects.all()

    return render(request, "depart_list.html", {"depart_list": depart_list})

def depart_add(request):
    """部门添加"""
    if request.method == "GET":
        return render(request, "depart_add.html")

    # 获取用户提交的部门数据
    depart_title = request.POST.get("depart_title")

    # 保存到数据库
    models.Department.objects.create(title=depart_title)

    return redirect("/depart/list/")



def depart_del(request):
    """部门删除"""
    # 获取部门id
    depart_id = request.GET.get("depart_id ")

    # 根据部门id删除部门
    models.Department.objects.filter(id=depart_id).delete()

    return redirect("/depart/list/")


def depart_edit(request, id):
    """部门编辑"""
    if request.method == "GET":

        # 获取部门id
        row_object=models.Department.objects.filter(id=id).first()


        return render(request, "depart_edit.html", {"row_object": row_object})
    title = request.POST.get("depart_title")
    models.Department.objects.filter(id=id).update(title=title)
    return redirect("/depart/list")


# def user_list(request):
#     """用户列表"""
#     user_list = models.UserInfo.objects.all()
#
#     print(user_list)
#     return render(request, "user_list.html", {"user_list": user_list})


def user_list(request):
    """用户列表"""
    # 获取所有用户列表
    user_list = models.UserInfo.objects.all()

    page_object = Pagination(request, user_list, page_size=10 )

    # 用 python 的语法获取数据
    """
    for obj in user_data:
        # obj.get_gender_display() 表示匹配 男/女,原始字段名为gender,obj.get_字段名称_display()
        # obj.create_time.strftime("%Y-%m-%d") 表示将时间格式转换成固定格式的字符串
        # obj.depart.title 表示获取depart_id对应的部门名称,因为我们在models中定义表时与另外一张表设置了级联关系,有外键
        print(obj.id, obj.name, obj.password, obj.age, obj.account, obj.get_gender_display(), obj.depart.title, obj.create_time.strftime("%Y-%m-%d"))
    """

    page_object.html()

    context = {
        "user_list": page_object.page_queryset,
        "page_string": page_object.page_string,
    }

    return render(request, "user_list.html", context)








class UserModelForm(BootstrapModelForm):
    class Meta:

            model = models.UserInfo
            fields = ['name', 'password','age','sex','create_time','account','depart']

# class UserModelForm(forms.ModelForm):
#     class Meta:
#         model = models.UserInfo
#         fields = ['name', 'password','age','sex','create_time','account','depart']
#         #插件
#         # widgets = {
#         # "name": forms.TextInput(attrs={"class": "form-control", "placeholder": ""})
#         # }
#
#         #使用BootstrapModelForm类,可以自动生成form表单的样式
#     # def __init__(self, *args, **kwargs):
#     #     super().__init__(*args, **kwargs)
#     #     for name,field in self.fields.items():
#     #         field.widget.attrs={"class" :"form-control"}

def user_add1(request):
    """用户添加"""
    if request.method == "GET":
        form=UserModelForm()
        return render(request, "user_add1.html",{"form":form})

    #数据效验
    form=UserModelForm(request.POST)
    if form.is_valid():
        form.save()
    else:print(form.errors)

    return redirect("/user/list/")




def user_add(request):
    """用户添加"""
    context={
        "gender_list":((1,"男"),(2,"女")),
        "depart_list" : models.Department.objects.all()
    }
    if request.method == "GET":


        return render(request, "user_add.html",context)
        #return render(request, "user_add.html",{"form":form})


    if request.method == "POST":
        name = request.POST.get("name")
        password = request.POST.get("password")
        gender = request.POST.get("gender")
        age = request.POST.get("age")
        depart_id = request.POST.get("department")
        create_time=request.POST.get("create_time")
        account = request.POST.get("account")
        models.UserInfo.objects.create(name=name,password=password,sex=gender,depart_id=depart_id,age=age,create_time=create_time,account=account)


    return redirect("/user/list/")












def user_edit(request,id):
    """用户编辑"""
    row_object=models.UserInfo.objects.filter(id=id).first()
    if request.method == "GET":


        form = UserModelForm(instance=row_object)



        return render(request, "user_edit.html",{"id":id,"form":form})



    form=UserModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")
    else:
        print(form.errors)
        return render("user_edit.html", {"form":form})







def user_del(request):
    """用户删除"""
    if request.method == 'GET':
        nid=request.GET.get("nid")
        models.UserInfo.objects.filter(id=nid).delete()
        return redirect("/user/list/")





# def num_list(request):
#
#     """用户列表"""
#     num_list = models.PrettyNum.objects.all()
#
#     print(num_list)
#     return render(request, "num_list.html", {"num_list": num_list})


def num_list(request):
    """靓号列表"""

    # page_now = int(request.GET.get('page', 1))
    #
    # page_range = 5  # 当前页面前后留几个页码
    # start = (page_now - 1) * 10
    # end = page_now * 10 + 2
    #
    # # 总数据行数
    # data_num = models.PrettyNum.objects.all().count()
    #
    # # 总页码
    # page_num, div = divmod(data_num, 10)
    # if div:
    #     page_num += 1
    #
    # page_show = 5
    # # 如果总页码数量大于 11
    # if page_num > page_show * 2 + 1:
    #     # 如果当前页面页码位置小于等于5
    #     if page_now <= 5:
    #         start_page = 1
    #         end_page = page_show * 2 + 2
    #     # 否则,当前页面页码位置大于5时
    #     else:
    #         # 防止页码超出范围
    #         if page_now >= page_num - page_show:
    #             start_page = page_num - page_show * 2
    #             end_page = page_num + 1
    #         else:
    #             # 计算出当前页的前5页和后5页
    #             start_page = page_now - page_show
    #             end_page = page_now + page_show + 1
    #
    # else:
    #     start_page = 1
    #     end_page = page_num + 1
    #
    # ######## 创建页码 ########
    # # 页码
    # page_str_list = []
    #
    # # 跳到首页
    # head_page = '?page={}'.format(1)
    #
    # # 跳到上10页
    # # 如果当前页面小于 11, 防止超过最小页数
    # if page_now < page_show * 2 + 1:
    #     prev = '<li><a href="?page={}">{}</a></li>'.format(1, "<<")
    #     page_str_list.append(prev)
    # else:
    #     prev = '<li><a href="?page={}">{}</a></li>'.format(page_now - 10, "<<")
    #     page_str_list.append(prev)
    #
    # for i in range(start_page, end_page):
    #
    #     # 如果是当前页,高亮显示页码颜色
    #     if page_now == i:
    #         ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
    #     else:
    #         ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
    #     page_str_list.append(ele)
    #
    # ### 跳到下10页
    # # 如果当前页面页数 大于 最大页面数量减去(page_show*2+1),则直接跳到最后一页,防止超过最大页数
    # if page_now >= page_num - page_show * 2 + 1:
    #     next = '<li><a href="?page={}">{}</a></li>'.format(page_num, ">>")
    #     page_str_list.append(next)
    # else:
    #     next = '<li><a href="?page={}">{}</a></li>'.format(page_now + 10, ">>")
    #     page_str_list.append(next)
    #
    # page_string = mark_safe("".join(page_str_list))
    #
    # # 跳到尾页
    # end_page = '?page={}'.format(page_num)
    #
    # ################### 代码实现分页结束 ###################
    #





    data_dict = {}

    search_data = request.GET.get('query', "")  # 不加后面的 "", 首次访问浏览器,搜索框中不会显示前端页面中的 placeholder="Search for..." 属性
    if search_data:
        data_dict["mobile__contains"] = search_data

    num_data = models.PrettyNum.objects.filter(**data_dict).order_by("id")


#################分页代码#########


    page_object = Pagination(request, num_data, page_size=10, page_param="page")
    page_queryset = page_object.page_queryset

    # 调用对象的html方法,生成页码
    page_object.html()

    page_string = page_object.page_string
    head_page = page_object.head_page
    end_page = page_object.end_page

    context = {
        "num_data": page_queryset,  # 分页的数据
        "search_data": search_data,  # 搜索的内容
        "page_string": page_string,  # 页码
        "head_page": head_page,  # 首页
        "end_page": end_page,  # 尾页
    }

    return render(request, "num_list.html", context)


    # 加入search_data的目的是,当搜索后,搜索框内的值不会置为空
    #return render(request, "num_list.html", {"num_data": num_data, "search_data": search_data})


def num_del(request):
    """删除"""
    if request.method == 'GET':
        nid=request.GET.get("nid")
        models.PrettyNum.objects.filter(id=nid).delete()
        return redirect("/num/list/")





class NumModelForm(forms.ModelForm):
    def clean_mobile(self):
        txt_mobile = self.cleaned_data['mobile']

        if len(txt_mobile) != 11:
            # 验证不通过
            raise ValidationError('格式错误')

        # 验证通过
        return txt_mobile




    class Meta:
        model = models.PrettyNum
        fields = ['mobile','price','status','level']
        # widgets = {
        # "name": forms.TextInput(attrs={"class": "form-control", "placeholder": ""})
        # }
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name,field in self.fields.items():
            field.widget.attrs={"class" :"form-control"}



from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=models.PrettyNum)
def update_id(sender, instance, **kwargs):
    if instance.id is None:
        last_id = models.PrettyNum.objects.all().order_by('-id').first().id
        instance.id = last_id + 1 if last_id else 1
def num_add(request):
    """添加"""
    if request.method == "GET":
        form=NumModelForm()
        return render(request, "num_add.html",{"form":form})

    #数据效验
    form=NumModelForm(request.POST)
    if form.is_valid():
        form.save()
    else:print(form.errors)

    return redirect("/num/list/")


class PrettyEditModelForm(forms.ModelForm):
    mobile=forms.CharField(disabled=True,label="手机号")
    class Meta:
        model = models.PrettyNum
        # fields = "__all__"    表示取表中所有的字段
        fields = ['mobile','price', 'level', 'status']
        # exclude = ['level']   表示取除了表中的某个字段的所有字段

    # 循环找到所有的插件,加入css样式,添加 "class": "form-control"
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            print(name, field)
            field.widget.attrs = {"class": "form-control"}




def num_edit(request,id):
    """用户编辑"""
    row_object=models.PrettyNum.objects.filter(id=id).first()
    if request.method == "GET":


        form = NumModelForm(instance=row_object)



        return render(request, "num_edit.html",{"id":id,"form":form})



    form=NumModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/num/list/")
    else:
        print(form.errors)
        return render("num_edit.html", {"form":form})


